package com.copa.l231;

/**
 * @author copa
 * @createDate 2022-05-30 14:53
 * @function 二分查找法
 */
public class Test3 {

    public boolean isPowerOfTwo(int n) {
        // 假设 2^x = n 尝试 left <= x <= right
        int left = 0;
        int right = n;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (Math.pow(2, mid) > n) {
                // 若2^mid > n
                right = mid - 1;
            } else if (Math.pow(2, mid) < n) {
                // 若2^mid < n
                left = mid + 1;
            } else {
                // 若 2^mid = n 那就证明是2的幂
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        System.out.println(new Test3().isPowerOfTwo(16));
    }
}
